package com.dem.android.service;

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;

import com.dem.android.util.Config;
import com.dem.android.util.DemsProcessor;

/**
 * DataUpdateService - manages connection to server, retrieves data from it,
 * parses the response and updates database with new values in background
 * thread.
 */
public class UpdateService extends IntentService {

	private static final String TAG = UpdateService.class.getSimpleName();

	public static final String EXTRA_STATUS_RECEIVER = "extra_receiver";
	public static final String EXTRA_REQUEST_CODE = "request_code";
	public static final String ERROR_MESSAGE = "err_msg";
	public static final String RECORDS = "records";

	public static final int STATUS_RUNNING = 1;
	public static final int STATUS_ERROR = 2;
	public static final int STATUS_FINISHED = 3;

	public final static String BASE_URL_RU = "http://demotivators.ru";
	private final String URL_DEM_RU = BASE_URL_RU.concat("/?page=");
	
	public final static String BASE_URL_US = "http://demotivationalpost.com/";

	private int queryCode;
	private int page;

	private DemsProcessor demsProccesor;

	public UpdateService() {
		super(TAG);
	}

	@Override
	public void onCreate() {
		super.onCreate();
		demsProccesor = new DemsProcessor();
	}

	/**
	 * This method manages sends request to a server, parses response from it
	 * and updates database with new values.
	 */
	@Override
	protected void onHandleIntent(final Intent intent) {

		final ResultReceiver receiver = intent.getParcelableExtra(EXTRA_STATUS_RECEIVER);

		queryCode = intent.getIntExtra(Config.DEM_TYPE, Config.DEM_RU);
		page = intent.getIntExtra(Config.PAGE, 1);
		final Bundle resultData = new Bundle();

		try {
			switch (queryCode) {
			case Config.DEM_RU:
				demsProccesor.processDemsRu(getContentResolver(), URL_DEM_RU.concat(String.valueOf(page)), page, Config.DEM_RU_TYPE);
				receiver.send(STATUS_FINISHED, resultData);
				break;
			case Config.DEM_US:
				demsProccesor.processDemsUs(getContentResolver(), BASE_URL_US.concat(String.valueOf(page)), page, Config.DEM_US_TYPE);
				receiver.send(STATUS_FINISHED, resultData);
				break;
			default:
				break;
			}

		} catch (Exception ex) {
			Log.e(TAG, ex.getMessage(), ex);
			final Bundle errInfo = new Bundle();
			errInfo.putString(ERROR_MESSAGE, "No internet connection...");
			if (null != receiver)
				receiver.send(STATUS_ERROR, errInfo);
		}
	}
}
